package com.gcloud.mesh.dcs.chain.k8s;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.CloudResourceConfigDao;
import com.gcloud.mesh.asset.entity.CloudResourceConfigEntity;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import com.gcloud.mesh.dcs.dao.AppInstanceDao;
import com.gcloud.mesh.dcs.dao.SchedulerAdviceDao;
import com.gcloud.mesh.dcs.dao.SchedulerJobDao;
import com.gcloud.mesh.dcs.dao.SchedulerStepDao;
import com.gcloud.mesh.dcs.entity.SchedulerStepEntity;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.GcePageReply;
import com.gcloud.mesh.sdk.gce.NamespaceVo;
import com.gcloud.mesh.supplier.enums.SystemType;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.MyBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class UpdateClusterConfig implements IMigrationStepChain {

    @Autowired
    private CloudResourceConfigDao cloudResourceConfigDao;

    @Autowired
    private SchedulerStepDao schedulerStepDao;
    
    @Autowired
    private AppInstanceDao appInstanceDao;

    @Autowired
    private SchedulerJobDao schedulerJobDao;

    @Autowired
    private SchedulerAdviceDao schedulerAdviceDao;



    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        filterChain.doExec(schedulerJobId,attach,filterChain,stepChain);
    }

    @Override
    public boolean checkStatus(String stepId) {
        try {
            SchedulerStepEntity stepEntity = schedulerStepDao.getById(stepId);
            JSONObject jsonObject = JSONObject.parseObject(stepEntity.getAttach());
            String dstCloudResourceId = jsonObject.getString("dstCloudResourceId");
            String instanceName = jsonObject.getString("instanceName");
            String instanceId = jsonObject.getString("instanceId");
            CloudResourceConfigEntity configEntity = cloudResourceConfigDao.findOneByProperty("cloudResourceId", dstCloudResourceId);
            if (configEntity == null) throw new MyBusinessException("找不到云资源配置信息，请稍候再试");
            GceSDK gceSdk = SpringUtil.getBean(GceSDK.class);
            String clusterId = configEntity.getClusterId();
            GcePageReply<NamespaceVo> namespacePage = gceSdk.pageNamespace(clusterId, 1, Integer.MAX_VALUE);
            List<NamespaceVo> namespaceVoList = namespacePage.getData();
            if (namespaceVoList == null || namespaceVoList.isEmpty()) throw new MyBusinessException("更新应用失败，请稍候再试");
            for (NamespaceVo namespaceVo : namespaceVoList) {
                if (namespaceVo.getName().equals(instanceName)) {
                    // int result = jdbcTemplate.update("update dcs_app_instance set instance_id = ? where instance_id = ?", namespaceVo.getId(), instanceId);
                    String jobId = stepEntity.getSchedulerJobId();
                    String srcInstanceId = instanceId;
                    String dstInstanceId = namespaceVo.getId();
                    log.info("迁移完成更新appinstance表数据："+srcInstanceId);
                    appInstanceDao.updateAppIdBySrcId(srcInstanceId, dstInstanceId);
                    log.info("迁移完成更新job表数据："+srcInstanceId);
                    int result = schedulerJobDao.updateJobInstanceId(jobId, dstInstanceId);
                    log.info("迁移完成删除建议表数据："+srcInstanceId);
                    schedulerAdviceDao.deleteByInstanceId(srcInstanceId);
//                    int result = appService.updateInstanceDBInfo(stepEntity.getSchedulerJobId(), instanceId, namespaceVo.getId());
                    if (result > 0) return true;
                }
            }
            return false;
        }catch (Exception e){
            log.error("UpdateClusterConfig",e);
            return false;
        }
    }

    @Override
    public boolean isSyncChain() {
        return false;
    }

    @Override
    public String chainType() {
        return SystemType.K8S.getName();
    }

    @Override
    public String chainName(String attach) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        return String.format("%s更新应用信息",jsonObject.getString("dstDatacenterName"));
    }

    @Override
    public int getOrder() {
        return 5;
    }
}
